<?php
namespace app\api\service;


use app\api\model\App;
use app\api\model\Order;
use GuzzleHttp\Client;
use think\facade\Log;

class NoticeService{
    public function send(Order $order, App $app):bool{
        if(!$app->callback){
            return true; 
        }
        $data = [
            'order_no' => $order->order_no,
            'trade_no' => $order->trade_no,
            'amount' => $order->amount,
            'pay_type' => $order->pay_type,
            'pay_time' => $order->pay_time, 
        ];
        $data['sign'] = $this->sign($data, $app->appsecret);
        try{
            $response = (new Client())->post($app->callback, [
                'json' => $data,
                'timeout' => 10,
            ]);
            if($response->getStatusCode() == 200){
                $body =$response->getBody();
                Log::info('回调响应', ['response' => $body]);
                return strtolower(trim($body)) === 'success';
            }
        }catch(\Exception $e){
            Log::error('回调请求失败', [
                'url' => $app->callback,
                'error' => $e->getMessage(),
                'order_id' => $order->id
            ]);
            return false;
        }
        return false;
    }
    private function sign($data, $key) {
        ksort($data);
        $signStr = '';
        $signStr = implode('&', array_map(function($k, $v) {
            return $k . '=' . $v;
        }, array_keys($data), $data));
        $signStr .=  $key;
        return md5($signStr);
    }
}